//
//  IOS7SearchController.m
//  SanYiSanDemo
//
//  Created by GZMLUser on 14-10-28.
//  Copyright (c) 2014年 GZMLUser. All rights reserved.
//

#import "IOS7SearchController.h"
#define preViewWith 220
#define previewHeigth 220
#define previewX 50
#define previewY 60
#define GreenImageSize 15 // 扫描框四角图片大小
#define GroundAlpha 0.8 // 四周view的透明度

#define IOS7 [[[UIDevice currentDevice] systemVersion]floatValue]>=7

@interface IOS7SearchController ()
{
    NSTimer *_timer;
    BOOL _upOrdown;
    NSInteger num;
}
@end

@implementation IOS7SearchController
- initIOS7SearchWithDelegate:(id<IOS7SearchDelegete>)scanDelegate
{
    self.delegate = scanDelegate;
    
    if (self) {
        return self;
    }
    
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _upOrdown = NO;
    num = 0;
    self.title = @"扫描二维码";
}

#pragma mark - 设置UI
- (void)buildUI
{
    self.view.backgroundColor = [UIColor clearColor];
    self.view.frame = [UIScreen mainScreen].bounds;
    NSLog(@"view:%@",NSStringFromCGRect(self.view.frame));
    // 扫描线条
    self.lineView = [[UIImageView alloc]initWithFrame:CGRectMake(previewX, previewY,preViewWith, 4)];
    self.lineView.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:self.lineView];
    //[self.view bringSubviewToFront:self.lineView];
    UIImageView *groundView = [[UIImageView alloc]initWithFrame:CGRectMake(previewX , previewY , preViewWith , previewHeigth )];
    groundView.backgroundColor = [UIColor clearColor];
    [groundView.layer setBorderWidth:1];
    [groundView.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.view addSubview:groundView];
    
    // 扫描框四个角
    UIImageView *left = [[UIImageView alloc]initWithFrame:CGRectMake(previewX, previewY, GreenImageSize, GreenImageSize)];
    left.image = [UIImage imageNamed:@"QRCodeCorner_LeftTop.png"];
    [self.view addSubview:left];
    
    UIImageView *rigth = [[UIImageView alloc]initWithFrame:CGRectMake(previewX + preViewWith - GreenImageSize, previewY, GreenImageSize, GreenImageSize)];
    rigth.image = [UIImage imageNamed:@"QRCodeCorner_RightTop.png"];
    [self.view addSubview:rigth];
    
    UIImageView *left1 = [[UIImageView alloc]initWithFrame:CGRectMake(previewX, previewY + previewHeigth - GreenImageSize, GreenImageSize, GreenImageSize)];
    left1.image = [UIImage imageNamed:@"QRCodeCorner_LeftButtom.png"];
    [self.view addSubview:left1];
    
    UIImageView *rigth1 = [[UIImageView alloc]initWithFrame:CGRectMake(previewX + preViewWith - GreenImageSize, previewY + previewHeigth - GreenImageSize, GreenImageSize, GreenImageSize)];
    rigth1.image = [UIImage imageNamed:@"QRCodeCorner_RightButtom.png"];
    [self.view addSubview:rigth1];
    
    // 添加扫描框四周遮屏效果
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, previewY)];
    topView.alpha = GroundAlpha;
    topView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:topView];
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,previewY, previewX, previewHeigth)];
    leftView.alpha = GroundAlpha;
    leftView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:leftView];
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(previewX + preViewWith, previewY, 320 - (preViewWith + previewX),previewHeigth)];
    rightView.alpha = GroundAlpha;
    rightView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:rightView];
    
    UIView *lowerView = [[UIView alloc]initWithFrame:CGRectMake(0, previewY + previewHeigth, 320, self.view.frame.size.height - (previewY + previewHeigth))];
    lowerView.alpha = GroundAlpha;
    lowerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:lowerView];
    // 提示框
    UILabel  *tishiLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, previewHeigth + previewY + 30, 320, 50)];
    tishiLabel.backgroundColor = [UIColor clearColor];
    tishiLabel.textAlignment = NSTextAlignmentCenter;
    tishiLabel.text = @"请将二维码置于方框内扫描";
    tishiLabel.textColor = [UIColor whiteColor];
    [tishiLabel setFont:[UIFont systemFontOfSize:16.0f]];
    [self.view addSubview:tishiLabel];
}

#pragma mark - linView扫描
- (void)lineViewAnimation
{
    // 设置扫描动画
    if (_upOrdown == NO) {
        num ++;
        _lineView.frame = CGRectMake(previewX, previewY+2*num, preViewWith, 2);
        if (2*num == previewHeigth) {
            
            _lineView.frame = CGRectMake(previewX, previewY, preViewWith, 2);
            num = 0;
            _upOrdown = YES;
        }
    }
    else {
        _upOrdown = NO;
    }
}


#pragma mark - 开始扫描
- (void)startIOS72DSearch
{
    if (self.captureSession) {
        
        [self.captureSession startRunning];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(lineViewAnimation) userInfo:nil repeats:YES];
    }
    else
    [self startReading];
}
- (void)stopIOS72DSearch // 结束
{
    if (self.captureSession) {
        
        [self endReading];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self buildUI]; // 设置UI
    
    [self startReading]; // 开始扫描
    
}

#pragma mark -开始扫描
- (void)startReading
{
    NSError *error;
    
    // 设备
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 输入
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        
    }
    
    _captureSession = [[AVCaptureSession alloc] init];
    _captureSession.sessionPreset = @"AVCaptureSessionPreset1920x1080";// 设置图片输出像素
    [_captureSession addInput:input];
    // 输出
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:captureMetadataOutput];

    [self ajustSearchLocation:CGRectMake(previewX, previewY, preViewWith, previewHeigth) andCaptureOutput:captureMetadataOutput];

    // 设置输出代理，及类型
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
   
    _previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    
    [_captureSession startRunning];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(lineViewAnimation) userInfo:nil repeats:YES];
}

#pragma mark -调整扫描位置
- (void)ajustSearchLocation:(CGRect)rect andCaptureOutput:(AVCaptureMetadataOutput*)captureOutput
{
    CGSize size = self.view.bounds.size;
    CGRect cropRect = rect;
    CGFloat p1 = size.height/size.width;
    CGFloat p2 = 1920./1080.;  //使用了1080p的图像输出
    if (p1 < p2) {
        CGFloat fixHeight = self.view.bounds.size.width * 1920. / 1080.;
        CGFloat fixPadding = (fixHeight - size.height)/2;
        captureOutput.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight,
                                                  cropRect.origin.x/size.width,
                                                  cropRect.size.height/fixHeight,
                                                  cropRect.size.width/size.width);
    } else {
        CGFloat fixWidth = self.view.bounds.size.height * 1080. / 1920.;
        CGFloat fixPadding = (fixWidth - size.width)/2;
        captureOutput.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                                  (cropRect.origin.x + fixPadding)/fixWidth,
                                                  cropRect.size.height/size.height,
                                                  cropRect.size.width/fixWidth);
    }
    
}

#pragma mark -结束扫描
- (void)endReading
{
    [self.captureSession stopRunning];
    
    if (self.delegate) {
        
        [self.delegate ios7SearchControllerDidCancel:self];
    }
    if (_captureSession.inputs.count > 0) {
        AVCaptureInput* input = [_captureSession.inputs objectAtIndex:0];
        [_captureSession removeInput:input];
    }
    AVCaptureVideoDataOutput* output = (AVCaptureVideoDataOutput*)[_captureSession.outputs objectAtIndex:0];
    [_captureSession removeOutput:output];
    [self.previewLayer removeFromSuperlayer];
    
    self.previewLayer = nil;
    self.captureSession = nil;
    
    
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        // 条形码
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            
            [self performSelectorOnMainThread:@selector(dealWithQRCode:) withObject:metadataObj.stringValue waitUntilDone:NO];
            
            [_timer invalidate];
        }
        
        // 其他类型再次添加操作
        
    }
}

#pragma mark 扫描类型处理方法
- (void)dealWithQRCode:(NSString *)object // 二维码
{
    // 对二维码处理,通过代理实现传参
    if (self.delegate != nil) {
        
        [self.delegate ios7SearchController:self didScanResult:object];
    }
    
    [self endReading]; // 结束扫描
    
}

@end
